package com.yatb.trac.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.yatb.trac.pojo.StoricoTicket;
import com.yatb.trac.pojo.Tickets;
import com.yatb.trac.pojo.Utenti;
import com.yatb.trac.pojo.comparator.OrderBy;
import com.yatb.trac.pojo.comparator.StoricoTicketOrderByDataModifica;
import com.yatb.trac.pojo.wrappers.StoricoTicketWrapper;
import com.yatb.trac.pojo.wrappers.UtentiView;
import com.yatb.trac.service.SearchService;
import com.yatb.trac.util.SQLCondition;
import com.yatb.trac.util.StatoConstant;

public class DettaglioTicketController extends AbstractController {

	private String view;
	private SearchService searchService;

	private long twentyFourHoursInMs = 1000 * 60 * 60 * 24;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView modelAndView = new ModelAndView(getView());
		Utenti utenteLoggato =((UtentiView) request.getSession(false).getAttribute("loginForm")).getUtenti();
		SQLCondition sqlCondition = new TicketFinderByIdTicket(request
				.getParameter("id"));
		Tickets ticket = getSearchService().find(new Tickets[0], sqlCondition,
				Tickets.class)[0];
		request.setAttribute("showDescrizione", new Boolean(true));
		Set<StoricoTicket> setStorico = ticket.getStoricoTickets();
		StoricoTicket[] st = setStorico.toArray(new StoricoTicket[0]);
		Arrays.sort(st, new StoricoTicketOrderByDataModifica(OrderBy.DESC));
		List<StoricoTicketWrapper> wrappers = new ArrayList<StoricoTicketWrapper>();
		for (int i = 0; i < st.length; i++) {
			StoricoTicket storicoTicket = st[i];
			
			boolean isModifiable = new Date().getTime()
					- storicoTicket.getDataModifica().getTime() < twentyFourHoursInMs
					&& !ticket.getStati().getIdStato().toPlainString().equals(
							"3") ;
			isModifiable =  isModifiable && (utenteLoggato.getIdUtente().toPlainString().equals(storicoTicket.getUtenti().getIdUtente().toPlainString()));
			if(i!=0){
				isModifiable=false;
			}
			StoricoTicketWrapper aWrapper = new StoricoTicketWrapper(
					storicoTicket, isModifiable);
			wrappers.add(aWrapper);
		}
		request.setAttribute("storico", wrappers);
		request.setAttribute("ticket", ticket);

		return modelAndView;
	}

	public String getView() {
		return view;
	}

	public void setView(String view) {
		this.view = view;
	}

	public SearchService getSearchService() {
		return searchService;
	}

	public void setSearchService(SearchService searchService) {
		this.searchService = searchService;
	}

}
